package io.ganguo.chat.route.client.handler;

import io.ganguo.chat.core.connetion.IMConnection;
import io.ganguo.chat.core.handler.IMHandler;
import io.ganguo.chat.core.protocol.Commands;
import io.ganguo.chat.core.protocol.Handlers;
import io.ganguo.chat.core.transport.Header;
import io.ganguo.chat.core.transport.IMRequest;
import io.ganguo.chat.core.transport.IMResponse;

/**
 * Created by hasee on 2016-04-01.
 */
public class HeartbeatHandler extends IMHandler<IMRequest> {
    @Override
    public short getId() {
        return Handlers.HEARTBEAT;
    }

    @Override
    public void dispatch(IMConnection connection, IMRequest request) {
        Header header = request.getHeader();
        switch (header.getCommandId()) {
            case Commands.CLIENT_HEARTBEAT:
                sendHeartbeat(connection, request);
                break;
            default:
                connection.close();
                break;
        }
    }

    private void sendHeartbeat(IMConnection connection, IMRequest request) {
        IMResponse resp = new IMResponse();
        Header header = new Header();
        header.setHandlerId(Handlers.HEARTBEAT);
        header.setCommandId(Commands.SERVER_HEARTBEAT);
        resp.setHeader(header);
        connection.sendResponse(resp);
    }
}
